package com.jsonal.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.jsonal.common.HttpUtil;
import com.jsonal.controller.BaseController;
import com.jsonal.entity.api.UserBean;
import com.jsonal.form.user.UserForm;
import com.jsonal.service.api.UserService;
import com.jsonal.vo.Result;
import io.swagger.annotations.ApiOperation;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Author: jingji.lin
 * @Description:
 * @Date: 2020/7/5 13:04
 * @Version: 1.0
 */
@Slf4j
@RequestMapping("/api")
@Controller
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/getUserInfo", method = RequestMethod.POST)
    @ApiOperation(value = "/getUserInfo", httpMethod = "POST", notes = "获取用户信息")
    @ResponseBody
    public Result getUserInfo(@RequestBody UserForm userForm) {
        UserBean userBean = new UserBean();
        this.setFormToBean3(userForm, userBean);
        return userService.getUserInfo(userBean);
    }

    @RequestMapping(value = "/getUserInfoBySso", method = RequestMethod.POST)
    @ApiOperation(value = "/getUserInfoBySso", httpMethod = "POST", notes = "获取用户信息，单点登录")
    @ResponseBody
    public Result getUserInfoBySso(@RequestBody UserForm userForm) {
        Map<String, Object> map = new HashMap<>();
        map.put("token", userForm.getToken());
        String str = HttpUtil
            .sendPost("http://localhost:7777/uaa/user/token", null, map);
        log.info("get请求返回的结果 >>>>>>>>>>>>>>>>>> {}", str);
        log.info("get请求返回的结果 >>>>>>>>>>>>>>>>>> {}", JSONObject.parseObject(str));
        String username = JSONObject.parseObject(str).getJSONObject("obj").getJSONObject("user").getString("username");
        UserBean userBean = new UserBean();
        userBean.setToken(userForm.getToken());
        userBean.setUsername(username);
        return userService.getUserInfo(userBean);
    }

    @RequestMapping(value = "/getUserById/{id}", method = RequestMethod.GET)
    @ApiOperation(value = "/getUserById/{id}", httpMethod = "GET", notes = "根据用户 id 获取信息")
    @ResponseBody
    public Result getUserById(@PathVariable String id) {
        if (id == null || "".equals(id)) {
            return new Result(false, "id不能为空");
        }
        return userService.getUserById(id);
    }
}
